package com.atguigu.service.impl;

import com.atguigu.annotations.MyRedisCache;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.entities.User;
import com.atguigu.service.UserService;
import com.atguigu.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * @author ASUS
 * @description 针对表【t_user(用户表)】的数据库操作Service实现
 * @createDate 2025-07-30 23:25:47
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    public static final String CACHE_KEY_USER = "user:";

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public boolean save(User user) {
        boolean retValue = false;
        log.info("插入之前user:{}", user);
        retValue = super.save(user);
        log.info("插入之后user:{}", user);
        log.info("=================================");
        if (retValue) {
            //到数据库里面，重新捞出新数据来，做缓存
            user = this.userMapper.selectById(user.getId());
            //缓存key
            String key = CACHE_KEY_USER + user.getId();
            //往mysql里面插入成功随后再从mysql查询出来，
            redisTemplate.opsForValue().set(key, user);
        }
        return retValue;
    }

    //    @Override
//    public User getById(Serializable id) {
//        User user = null;
//        //缓存key
//        String key = CACHE_KEY_USER + id;
//
//        //1.查询redis
//        user = (User) redisTemplate.opsForValue().get(key);
//
//        //2.如果redis有返回直接返回，redis没有进一步查询mysql
//        if(user == null){
//            //从mysql里面查询user
//            user = this.userMapper.selectById(id);
//            //3.mysql有，返回给redis 缓存补偿
//            if(user != null){
//                //把mysql捞到的数据写入redis 缓存补偿 方便下次查询能命中redis
//                redisTemplate.opsForValue().set(key,user);
//            }
//        }
//        return user;
//    }
    @Override
    @MyRedisCache(keyPrefix = "user",matchValue = "#id")
    public User getById(Serializable id) {
        //从mysql查出来user 如何将缓存代码从业务代码中剥离，促使业务代码更简洁更易维护
        return this.userMapper.selectById(id);
    }
}




